<script setup lang="ts">
import { ref, reactive, defineEmits, defineProps, watch, onMounted } from "vue";
import { ElMessage, ElForm, ElFormItem } from "element-plus";
import { updateAlertSceneApi, AlertSceneModel } from '@/api/alerts/alertScene';
import { useI18n } from 'vue-i18n';
import { useLogic } from "@/views/system/user/logic/logic";

const props = defineProps<{
  visible: boolean;
  scene: AlertSceneModel | null;
}>();

const emit = defineEmits<{
  'update:visible': [value: boolean];
  'success': [];
}>();

const { t } = useI18n();

const {deptTreeList,getDeptTree}  = useLogic()
onMounted(async () => {
  await getDeptTree();
})

// 表单数据
const formData = reactive<Partial<AlertSceneModel>>({
  name: '',
  englishName:'',
  type: '',
  deptId: 0,
  level: 0,
  frequency: 0,
  noticeType: '',
  remark: '',
  bindTo: 0,
  judgeMark: ''
});

// 表单验证规则
const rules = {
  name: [
    { required: true, message: t('alerts.scenePage.table.name') + ' ' + t('buttons.required'), trigger: 'blur' }
  ],
  judgeMark: [
    { required: true, message: t('alerts.scenePage.table.judgeMark') + ' ' + t('buttons.required'), trigger: 'change' }
  ],
  deptId: [
    { required: true, message: t('alerts.scenePage.table.dept') + ' ' + t('buttons.required'), trigger: 'change' }
  ],
  type: [
    { required: true, message: t('alerts.scenePage.table.type') + ' ' + t('buttons.required'), trigger: 'change' }
  ],
};

// 表单引用
const formRef = ref<InstanceType<typeof ElForm>>();

// 监听场景数据变化，更新表单
watch(() => props.scene, (newScene) => {
  if (newScene) {
    // 深拷贝场景数据到表单
    Object.assign(formData, { ...newScene });
    // 如果noticeType是字符串，需要转换为数组用于多选
    if (typeof formData.noticeType === 'string' && formData.noticeType) {
      // @ts-ignore
      formData.noticeType = formData.noticeType.split(',');
    }
  }
}, { immediate: true, deep: true });

// 关闭对话框
const handleClose = () => {
  emit('update:visible', false);
};

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
};

// 保存数据
const handleSave = async () => {
  if (!formRef.value || !props.scene) return;

  try {
    await formRef.value.validate();

    // 处理noticeType，如果是数组需要转为字符串
    const submitData = { ...formData };
    if (Array.isArray(submitData.noticeType)) {
      submitData.noticeType = submitData.noticeType.join(',');
    }

    const response = await updateAlertSceneApi(props.scene.id, submitData);
    if (response.code === 0) {
      ElMessage.success(t('alerts.scenePage.updateSuccess'));
      emit('success');
      handleClose();
    } else {
      ElMessage.error(response.msg || t('alerts.scenePage.updateFailed'));
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(t('alerts.scenePage.updateFailed'));
    }
  }
};

// noticeType选项
const noticeTypeOptions = [
  { label: 'Email', value: 'email' },
  { label: 'SMS', value: 'sms' }
];

// judgeMark选项
const judgeMarkOptions = [
  { label: '<', value: '<' },
  { label: '=', value: '=' },
  { label: '<=', value: '<=' },
  { label: '>', value: '>' },
  { label: '>=', value: '>=' }
];
</script>

<template>
  <el-dialog
    v-model="props.visible"
    :title="t('buttons.edit')"
    width="600px"
    @close="handleClose"
    draggable
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
    >
      <el-form-item :label="t('alerts.scenePage.table.name')" prop="name">
        <el-input v-model="formData.name" placeholder="" />
      </el-form-item>
      <el-form-item :label="t('alerts.scenePage.table.englishName')" prop="englishName">
        <el-input v-model="formData.englishName" placeholder="" />
      </el-form-item>
      <el-form-item :label="t('alerts.scenePage.table.type')">
        <el-input v-model="formData.type" placeholder="" />
      </el-form-item>
      <el-form-item :label="t('alerts.scenePage.table.level')">
        <el-input-number v-model="formData.level" :min="1" />
      </el-form-item>
      <el-form-item :label="t('alerts.scenePage.table.frequency')">
        <el-input-number v-model="formData.frequency" :min="1" />
        <span class="ml-2 text-sm text-gray-500">{{t('time.min')}}</span>
      </el-form-item>
      <el-form-item :label="t('alerts.scenePage.table.noticeType')">
        <el-select v-model="formData.noticeType" placeholder="" multiple>
          <el-option
            v-for="option in noticeTypeOptions"
            :key="option.value"
            :label="option.label"
            :value="option.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('products.devicePage.deptId')" prop="deptId">
        <el-cascader
          v-model="formData.deptId"
          class="w-full"
          :options="deptTreeList"
          :props="{
              value: 'id',
              label: 'name',
              emitPath: false,
              checkStrictly: true
            }"
          clearable
          filterable
          :placeholder="t('products.devicePage.deptId')"
        >
          <template #default="{ node, data }">
            <span>{{ data.name }}</span>
            <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
          </template>
        </el-cascader>
      </el-form-item>
      <el-form-item :label="t('alerts.scenePage.table.bindTo')">
        <el-radio-group v-model="formData.bindTo">
          <el-radio :label="0">{{ t('alerts.scenePage.bindTo.singleDevice') }}</el-radio>
          <el-radio :label="1">{{ t('alerts.scenePage.bindTo.group') }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item :label="t('alerts.scenePage.table.judgeMark')" prop="judgeMark">
        <el-select v-model="formData.judgeMark" placeholder="">
          <el-option
            v-for="option in judgeMarkOptions"
            :key="option.value"
            :label="option.label"
            :value="option.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('alerts.scenePage.table.remark')">
        <el-input v-model="formData.remark" type="textarea" :rows="3" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">{{ t('buttons.cancel') }}</el-button>
        <el-button type="primary" @click="handleSave">{{ t('buttons.save') }}</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
